package com.linsen.core.common.convert;

import com.fasterxml.jackson.annotation.JsonValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;

import java.lang.reflect.Field;

/** 枚举转字符串 */
@Slf4j
public class EnumToStringConverter implements Converter<Enum<?>, String> {

    @Override
    public String convert(Enum<?> source) {
        Class<?> enumType = source.getClass();

        Field[] fields = enumType.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(JsonValue.class)){
                try {
                    field.setAccessible(true);

                    return String.valueOf(field.get(source));
                } catch (IllegalAccessException e) {
                    log.error("enum map construct failed:", e);
                }
            }
        }

        return source.name();
    }
}
